#
# Copyright 2010 Steve Leach
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#

from datetime import datetime

from google.appengine.ext import db

from handlers import EveOpsHandler
from evedata import EveData, get_eve_data

class AwayRecord(db.Model):
	char_name = db.StringProperty(required=True)
	away_ts = db.DateTimeProperty(auto_now_add=True)
	activity = db.StringProperty()
	location = db.StringProperty()
	returning = db.BooleanProperty(required=True, default=True)

def add_awaylist_mappings(mappings):
	mappings.append(('/awaylist', AwayListHandler))
	mappings.append(('/going_away', GoingAwayHandler))
	mappings.append(('/arrived_home', ArrivedHomeHandler))
	mappings.append(('/submitaway', SubmitAwayHandler))
	mappings.append(('/submitarrived', SubmitArrivedHandler))

class AwayListHandler(EveOpsHandler):
	def get(self): 
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	

		list = AwayRecord.all()

		values = {'awaylist': list, 'eve_data': eve_data, 'headers': self.request.headers}

		self.display_page( 'awaylist.html', values )

class GoingAwayHandler(EveOpsHandler):
	def get(self): 
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	

		values = {'eve_data': eve_data, 'headers': self.request.headers}

		self.display_page( 'going_away.html', values )


class SubmitAwayHandler(EveOpsHandler):
	def post(self): 
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	
		
		awayrec = AwayRecord(char_name=self.request.get('char_name'))
		awayrec.activity = self.request.get('activity')
		awayrec.location = self.request.get('location')
		awayrec.returning = self.request.get('returning') == 'returning'
		awayrec.put()

		self.redirect('/awaylist')

class ArrivedHomeHandler(EveOpsHandler):
	def get(self): 
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	

		values = {'eve_data': eve_data, 'headers': self.request.headers}

		self.display_page( 'arrived_home.html', values )

class SubmitArrivedHandler(EveOpsHandler):
	def post(self): 
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	
		
		query = AwayRecord.gql('WHERE char_name = :1', self.request.get('char_name'))
		if query.count() > 0:
			query.get().delete()

		self.redirect('/awaylist')

